<template>
	<view class="equip_detail">
		<NavigationTitle title="流程详情" style="color: #000;background: #fff;position: fixed;width: 100%;z-index: 5;">
			<template slot="left_con">
				<image class="back_icon" src="@/static/common/back.png" mode="widthFix" @tap="backSelf" />
			</template>
		</NavigationTitle>
		<view class="status-bar"></view>
		<view class="main">
			<uni-forms ref="taskForm" :modelValue="baseFormData" class="form_main" :rules="rules">
				<uni-forms-item label="流程实例ID:" name="processInstanceId">
					<uni-easyinput v-model="baseFormData.processInstanceId" placeholder="请输入流程实例ID"
						:disabled="type=='edit'" />
				</uni-forms-item>
				<uni-forms-item label="执行实例ID:" name="executionId">
					<uni-easyinput v-model="baseFormData.processInstanceId" placeholder="请输入执行实例ID"
						:disabled="type=='edit'" />
				</uni-forms-item>
				<uni-forms-item label="业务编号:" name="businessKey">
					<uni-easyinput v-model="baseFormData.businessKey" placeholder="请输入业务编号"
						:disabled="type=='edit'"  />
				</uni-forms-item>
				<uni-forms-item label="任务名称:" name="taskName">
					<uni-easyinput v-model="baseFormData.taskName" placeholder="请输入任务名称"
						:disabled="type=='edit'"  />
				</uni-forms-item>
				<uni-forms-item label="流程名称:" name="processName">
					<uni-easyinput v-model="baseFormData.processName" placeholder="请输入流程名称"
						:disabled="type=='edit'"  />
				</uni-forms-item>
				<uni-forms-item label="启动时间:" name="startTime">
					<uni-datetime-picker type="datetime" v-model="baseFormData.startTime" placeholder="请选择启动时间" :disabled="type=='edit'" />
				</uni-forms-item>
				<uni-forms-item label="待审批人:" name="assignee">
					<view class="users_box" @click="()=>toggle(assignee)">
						<text>{{assignee}}</text>
					</view>
					<!-- <uni-easyinput type="textarea" v-model="users" placeholder="请选择设备绑定用户" :adjust-position='false'
						:disabled="!authorList.includes('system_device_edit')"
						@focus="(e)=>toggle(e,users)"></uni-easyinput> -->
				</uni-forms-item>
			</uni-forms>
			<button v-if="type=='add'" type="primary" @click="subUser" style="width: 50%; margin: auto;">提交</button>
			<button v-else-if="type=='edit'" type="primary" @click="completeTask"
				style="width: 50%; margin: auto;">审批</button>
		</view>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<DaTreeVue2 ref="DaTreeRef" :data="userTree" labelField="title" valueField="id" defaultExpandAll
					:showCheckbox="true" :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange" />
			</view>
		</uni-popup>
		<uni-popup ref="inputDialog" type="dialog" style="width: 100%;">
			<view class="popupDialog">
				<text class="title">审批结果</text>
				<view class="item">
					<text class="name">是否同意：</text>
					<uni-data-select v-model="resource" :clear="false" :localdata="[
					  { value: 0, text: '同意' },
					  { value: 1, text: '拒绝' },
					]" @change="changeResource"></uni-data-select>
				</view>
				<uni-easyinput type="textarea" v-model="comment" placeholder="请输入审批意见..." ></uni-easyinput>
				<view class="popupBtn">
					<button  type="reset" @click="dialogClose" style="width: 45%; margin: auto;">取消</button>
					<button  type="primary" @click="dialogConfirm" style="width: 45%; margin: auto;">确定</button>
				</view>
			</view>
			<!-- <uni-popup-dialog ref="inputClose" mode="input" title="审批结果" :value="comment" placeholder="请输入内容"
				confirmText="同意" cancelText="拒绝" @confirm="dialogConfirm" @close='dialogClose'></uni-popup-dialog> -->
		</uni-popup>
	</view>
</template>

<script>
	import NavigationTitle from '@/components/navigationTitle'
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	import {
		showToastMsg,
	} from '@/utils/format.js'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	export default {
		components: {
			NavigationTitle,
			DaTreeVue2
		},
		computed: {
			...mapGetters(['projectId', 'authorList', 'deviceType', 'deviceStatus', 'task'])
		},
		data() {
			return {
				type: 'add',
				title:'流程详情',
				rules: {
					businessKey: {
						rules: [{
							required: true,
							errorMessage: '业务编号不能为空！'
						}]
					},
					taskName: {
						rules: [{
							required: true,
							errorMessage: '任务名称不能为空！'
						}]
					},
					processName: {
						rules: [{
							required: true,
							errorMessage: '流程名称不能为空！'
						}]
					},
					startTime: {
						rules: [{
							required: true,
							errorMessage: '启动时间不能为空！'
						}]
					},
				},
				baseFormData: {},
				assignee: '',
				optionType: [],
				optionStatus: [],
				userTree: [],
				userList: [],
				defaultCheckedKeysValue: [],
				checkedKey: '',
				rootNodeKeys: [],
				resource: '',
				comment: '',
			}
		},
		onShow() {
			this.optionType = this.deviceType || []
			this.optionStatus = this.deviceStatus || []

		},
		async onLoad(option) {
			await this.getUserTree()
			if (option.type == 'edit') {
				this.baseFormData = this.task || {}
				this.assignee = this.getAssignee(this.task.assignee) || ''
			}
			this.type = option.type
		},
		methods: {
			getAssignee(str) {
				if (str) return str.slice(1, str.length - 1);
				else return ''

			},
			backSelf() {
				uni.navigateBack({
					delta: 1
				})
			},
			getUsers(arr) {
				let key = [],
					str = '',
					checked = []
				console.log(this.userList)
				this.userList.length > 0 && this.userList.map(v => {
					arr.map(i => {
						if (v.userId == i) {
							if (str == '') str = v.nickName
							else str += "," + v.nickName
							key.push(v.treeId)
							checked.push(v.userId)
						}
					})
				})
				this.defaultCheckedKeysValue = key
				this.assignee = str
				this.checkedKey = checked
				console.log(arr)
			},
			handleTreeChange(allSelectedKeys, currentItem) {
				let arr = ''
				let str = ''
				if (allSelectedKeys.length !== 0) {
					allSelectedKeys.map(v => {
						let index = v.indexOf('-')
						if (index != -1) {
							if (arr == '') arr = v.slice(index + 1)
							else arr += ',' + v.slice(index + 1)
						}
						this.userList.map(i => {
							if (i.treeId == v) {
								if (str == '') str = i.nickName
								else str += "," + i.nickName
							}
						})
					})
				}
				this.assignee = str
				this.checkedKey = arr

			},
			async getUserTree() {
				const res = await this.$api.getUserTree({
					projectId: this.projectId
				}).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					let arr = []
					if (res.data.length != 0) {
						res.data.map(v => {
							this.rootNodeKeys.push(v.id)
							if (v.userDtos.length > 0) {
								v.userDtos.map(i => {
									i.treeId = v.id + '-' + i.userId
									arr.push(i)
									v.children.push({
										id: v.id + '-' + i.userId,
										title: i.nickName + '+' + i.userPhone
									})
								})
							}
						})
					}
					this.userList = arr
					this.userTree = res.data
				}
			},
			toggle(data) {
				if(this.type=='edit') return 
				let arr = []
				if (data) {
					data.split(",").length > 0 && data.split(",").map(v => {
						this.userList.map(i => {
							if (i.nickName == v) {
								arr.push(i.treeId)
							}
						})
					})
				}
				this.defaultCheckedKeysValue = arr
				this.$refs.popup.open('bottom')
			},
			subUser() {
				let param = {}
				// if (!this.authorList.includes('system_device_edit')) return showToastMsg('无修改权限！')
				if(!this.task.taskId) return 
				this.$refs.taskForm.validate().then(res => {
					console.log(res)
					return 
					param = res
					param.assignee = this.checkedKey
					param.project = this.projectId
					if (this.type == 'add') this.addEquip(param)
					else if (this.type == 'edit') this.editEquip(param)
				}).catch(err => {
					console.log(err)
				})

			},
			completeTask() {
				this.comment=''
				this.resource=null
				this.$refs.inputDialog.open()
			},
			async dialogConfirm() {
				if(!this.task.taskId) return 
				if(!this.comment||!this.resource) return showToastMsg('请输入审批结果')
				let obj = {
					comment:this.comment,
					resource:this.resource,
					taskId:this.task.taskId
				}
				return 
				const res = await this.$api.completeTask(obj).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					setTimeout(() => {
						this.backSelf()
					}, 1000)
				}
				showToastMsg(res.msg)
				this.$refs.inputDialog.close()
			},
			dialogClose(){
				this.$refs.inputDialog.close()
			},
			changeResource(e){
				console.log(e)
			},	
			async addEquip(data) {
				let that = this
				const res = await this.$api.addEquipment(data).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					setTimeout(() => {
						that.backSelf()
					}, 1000)
				}
				showToastMsg(res.msg)
			},
			async editEquip(data) {
				let that = this
				if (this.device.id) data.id = this.device.id
				else return
				const res = await this.$api.editEquipment(data).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					setTimeout(() => {
						that.backSelf()
					}, 1000)
				}
				showToastMsg(res.msg)
			},
			changeRole(e) {
				console.log(e);
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/assets/styles/global.scss';

	view {
		box-sizing: border-box;
	}

	/deep/ .uni-modal__textarea {
		height: 100rpx;
	}

	.equip_detail {
		position: relative;
		height: 100%;
	}

	.form_main {
		padding: 40rpx 20rpx;
		min-height: 550rpx;

		.form-item {
			border-bottom: 1px solid #999;

			&>uni-view {
				margin-bottom: 24rpx;
			}

			.form-item-button {
				color: red;
			}

			.item-title {
				font-size: 32rpx;
			}
		}

		.users_box {
			width: 100%;
			height: 200rpx;
			padding: 10rpx;
			overflow: auto;
			border: 1px solid #ccc;
			border-radius: 20rpx;
			text-align: left;
			line-height: 50rpx;

			&>uni-text {
				font-size: 32rpx;
				word-break: keep-all;
			}
		}

		.uni-forms-item {
			flex-direction: column;

			/deep/ .uni-forms-item__label {
				width: auto;
				white-space: nowrap;
				font-size: 32rpx;
			}

			/deep/ .uni-forms-item__content {
				flex: 1;
				min-height: 70rpx;
				padding: 0 12rpx;
			}

			/deep/ .uni-input-placeholder {
				font-size: 28rpx;
			}

			/deep/ .uni-easyinput__placeholder-class {
				font-size: 28rpx;
			}

			/deep/ .uni-select__input-placeholder {
				font-size: 28rpx;
				color: #999;
			}
		}


	}

	.main {
		padding-top: $System__title_height;
	}

	.popup-content {
		max-height: 800rpx;
		min-height: 500rpx;
		overflow: auto;
		z-index: 999;
	}

	.popupDialog {
		background-color: #fff;
		width: 100%;
		height: 500rpx;
		overflow: auto;
		z-index: 999;
		padding: 30rpx;
		border-radius: 20rpx;
		.title{
			display: block;
			font-size: 36rpx;
			text-align: center;
		}
		.item{
			display: flex;
			align-items: center;
			margin: 20rpx 0;
		}
		.popupBtn{
			display: flex;
			justify-content: space-between;
			margin-top: 20rpx;
		}
	}

	/deep/ .uni-popup__wrapper {
		width: 80%;
	}

	.back_icon {
		width: 37upx;
	}
</style>